package justdoit.mvc.controllers;

import justdoit.spring.domain.Payment;
import justdoit.spring.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author nik
 */
@Controller
public class PaymentController {

    @Autowired(required = true)
    private PaymentService paymentService;

    @RequestMapping(value = "/")
    public String root() {
        return "payments";
    }

    @RequestMapping(value = "/payments")
    public String allPayments(Model model) {
        model.addAttribute("payments", paymentService.getPayments());
        return "payments.jsp";
    }
    
    @RequestMapping(value = "/add-payment", method = RequestMethod.GET)
    public String addPayment() {
        return "add-payment.jsp";
    }
    
    @ModelAttribute("payment")
    public Payment newPayment() {
        return new Payment();
    }
    
    @RequestMapping(value = "/payments", method = RequestMethod.POST)
    public String addPayment(@ModelAttribute("payment") Payment payment) {
        paymentService.addPayment(payment);
        return "redirect:payments";
    }
    
    @RequestMapping(value = "/payments/{id}", method = RequestMethod.GET)
    public String getPayment(@PathVariable("id") long id, Model model) {
        model.addAttribute("payment", paymentService.get(id));
        return "/payment.jsp";
    }
    
    @RequestMapping(value = "/payments/{id}", method = RequestMethod.GET, headers={"content-type=application/xml"}) 
    @ResponseBody public Payment getPayment(@PathVariable("id") long id) {
        return paymentService.get(id); 
    }
}